<template>

  <div class="form-container">
    <el-label>{{ labelContent }}</el-label>
    <el-form :model="standradlib_form" label-width="120px">
      <h2 class="form-title">标准库上传</h2>
      <el-form-item label="用户名">
        <el-input v-model="standradlib_form.user_name" placeholder="请输入用户名" :disabled="true"></el-input>
      </el-form-item>
      <el-form-item label="标注库名称">
        <el-input v-model="standradlib_form.name" placeholder="请输入标注库名称" required></el-input>
      </el-form-item>
      <el-form-item label="描述">
        <el-input v-model="standradlib_form.desc" placeholder="请添加描述" required></el-input>
      </el-form-item>
      <el-form-item label="文件上传">
        <el-upload ref="standardlibupload" :on-change="handleStandardlibFileChange" accept=".txt" :auto-upload="false"
          required>
          <el-button size="small" type="primary">选取文件</el-button>
        </el-upload>
        <el-button style="margin-left: 10px;" size="small" type="success"
          @click="submitStandardlibUpload">上传文件</el-button>
      </el-form-item>
    </el-form>

    <el-form :model="sample_form" label-width="120px" class="form-container">
      <h2 class="form-title">样本上传</h2>
      <el-form-item label="用户名">
        <el-input v-model="sample_form.user_name" placeholder="请输入用户名" required :disabled="true"></el-input>
      </el-form-item>
      <el-form-item label="样本名称">
        <el-input v-model="sample_form.sample_name" placeholder="请输入样本名称" required></el-input>
      </el-form-item>
      <el-form-item label="文件上传">
        <el-upload ref="upload" :on-change="handleFileChange" :action="uploadUrl" accept=".csv" :auto-upload="false"
          required>
          <el-button size="small" type="primary">选取文件</el-button>
        </el-upload>
        <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传文件</el-button>
      </el-form-item>
    </el-form>

    <div>
      <h2 class="form-title">样本训练</h2>
      <el-input-number v-model="sample_train_num" :min="1" :max="100" :step="1"
        placeholder="请输入训练次数"></el-input-number>
      <el-input v-model="new_model_name" placeholder="请输入新建模型名称"></el-input>

      <el-select v-model="sample_model_selectedOption" placeholder="请选择预训练的基础模型" class="sample_list_combox">
        <el-option v-for="item in sample_model_options" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select>

      <el-select v-model="sample_selectedOption" placeholder="请选择样本" class="sample_list_combox">
        <el-option v-for="item in sample_options" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select>
      
      <el-button type="primary" @click="queryData" class="input-button-container">查询</el-button>

      <el-button type="primary" @click="handleTrain" class="input-button-container">训练样本</el-button>
    </div>


    <div>
      <h2 class="form-title">推理</h2>
      <el-input-number v-model="top_num" :min="1" :max="100" :step="2"
        placeholder="请输入返回最相似的前几条结果"></el-input-number>

      <el-select v-model="standrad_selectedOption" placeholder="请选择标准库" class="sample_list_combox">
        <el-option v-for="item in standrad_options" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select>

      <el-select v-model="reason_model_selectedOption" placeholder="请选择模型库" class="sample_list_combox">
        <el-option v-for="item in reason_model_options" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select>

      <el-input v-model="text_list" placeholder="请输入文本列表，用逗号分隔" class="sample_list_combox"></el-input>

      <el-button type="primary" @click="handleQueryReasoningModel" class="input-button-container">查询</el-button>

      <el-button type="primary" @click="handleReasoning" class="input-button-container">推理</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import axios from 'axios'

const admin_name = 'admin';
const labelContent = ref(`默认用户名为 ${admin_name}`);





const sample_fileInput = ref(null);
const handleFileChange = (event) => {
  sample_fileInput.value = event.raw;
};

const sample_form = ref({
  sample_name: '',
  user_name: admin_name,
});
//上传样本;
const submitUpload = async () => {
  const formData = new FormData();
  formData.append('item', JSON.stringify(sample_form.value));
  formData.append('file', sample_fileInput.value);

  try {
    const response = await axios.post('http://localhost:8001/sample/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });

    alert('上传成功: ' + response.data.message);
  } catch (error) {
    let message = error.response.data.message;
    alert('上传失败: ' + message);
  }
};

const standradlib_form = ref({
  name: '',
  user_name: admin_name,
  desc: '',
});

const standardlib_fileInput = ref(null);
const handleStandardlibFileChange = (event) => {
  standardlib_fileInput.value = event.raw;
};
//上传标准库;
const submitStandardlibUpload = async () => {
  const formData = new FormData();
  formData.append('item', JSON.stringify(standradlib_form.value));
  formData.append('file', standardlib_fileInput.value);
  try {
    const response = await axios.post('http://localhost:8001/standrad/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });

    alert('上传成功: ' + response.data.message);
  } catch (error) {
    console.error('上传失败:', error);
    alert('上传失败: ' + error.message);
  }
}

//样表列表;
const sample_options = ref([]); // 用于存储从后端获取的选项数据
const sample_selectedOption = ref(null); // 用于存储当前选中的选项

//模型列表;
const sample_model_selectedOption = ref(null); // 用于存储当前选中的选项
const sample_model_options = ref([]); // 用于存储从后端获取的选项数据
const sample_train_num=ref(20); // 用于存储返回的结果数目

const new_model_name = ref(null); // 用于存储新建模型的名称



const handleSampleList = () => {
  axios.get('http://localhost:8001/sample/list',admin_name).then((response) => {
    let data = JSON.parse(response.data.message);
    sample_options.value=[];
    for (let i = 0; i < data.length; i++) {
      sample_options.value.push({
        value: data[i].sample_name,
      });

    }
  });

};
const ws_client_id = ref(null);

const createWebSocket = () => {
  if(ws_client_id.value!==null)
  {
    return;
  }
  const ws = new WebSocket('ws://localhost:8001/ws');
  ws.onopen = () => {
    console.log('websocket连接成功');
   
  };

  ws.onmessage = (event) => {
    let data=JSON.parse(event.data);
    if(data.type=="clientid")
    {
      ws_client_id.value = data.message;
      return;
    }
    alert( data.message);

  };
  ws.onclose = () => {
    console.log('websocket连接断开');
  };
  ws.onerror = (error) => {
    console.log('websocket连接错误:', error);
  };
};


const handleModelList = () => {
  
  let cert_data = {
    params: {
    user_name: admin_name
    }
  };
  axios.get('http://localhost:8001/model/list',cert_data).then((response) => {
    let data = JSON.parse(response.data.message);
    sample_model_options.value=[];
    for (let i = 0; i < data.length; i++) {
      sample_model_options.value.push({
        value: data[i].premodel_name,
      });
    }
  });
}

const queryData = () => {

  handleSampleList();
  handleModelList();
  createWebSocket();
}

const handleTrain = () => {

  if (sample_model_selectedOption.value.length == 0) {
    alert('请选择预训练模型库');
    return;
  }
  if (sample_selectedOption.value.length == 0) {
    alert('请选择样本');
    return;
  }
  if(new_model_name.value.length==0)
  {
    new_model_name.value=sample_model_selectedOption.value
  }

 

  let train_data = {
    user_name: admin_name,
    sample_name: sample_selectedOption.value,
    premodel_name: sample_model_selectedOption.value,
    num:sample_train_num.value,
    new_model_name: new_model_name.value,
    client_id:ws_client_id.value
  };

  axios.post('http://localhost:8001/model/train', train_data).then((response) => {

    console.log(response.data.message);
  });
}


const top_num = ref(5); // 用于存储返回的结果数目
// 推理相关;
const reason_model_selectedOption = ref(null); // 用于存储当前选中的选项
const reason_model_options = ref([]); // 用于存储从后端获取的选项数据
const standrad_options = ref([]); // 用于存储从后端获取的选项数据
const standrad_selectedOption = ref(null); // 用于存储当前选中的选项

const handleQueryReasoningModel = () => {

  //获取预训练模型列表;
  let cert_data = {
    params: {
    user_name: admin_name
    }
  };
  axios.get('http://localhost:8001/model/list',cert_data).then((response) => {
    let data = JSON.parse(response.data.message);
    for (let i = 0; i < data.length; i++) {
      reason_model_options.value.push({value:data[i].premodel_name});
    }
  });
  //获取标准库列表;
  axios.get('http://localhost:8001/standrad/list').then((response) => {
    let data = JSON.parse(response.data.message);
    for (let i = 0; i < data.length; i++) {
      standrad_options.value.push({value:data[i].name});
    }
  });

}
const handleReasoning = () => {

  let train_data = {
    premodel_name: reason_model_selectedOption.value,
    user_name: admin_name,
    top: top_num.value,
    standrad_name: standrad_selectedOption.value,
    text_list: ['支路6A相失灵', '0006跳A失灵启动']
  };


  axios.post('http://localhost:8001/model/reasoning', train_data).then((response) => {

    console.log(response.data);
  });

};
</script>

<style scoped>
.form-title {
  text-align: center;
  /* 标题居中 */
  margin-bottom: 20px;
  /* 标题与表单间距 */
}

.form-container {
  width: 500px;
  /* 根据需要调整宽度 */
  margin: 0 auto;
  /* 居中显示 */
}

.sample_list_combox {
  /* 可以添加自定义样式，例如宽度 */
  width: 450px;
  margin-bottom: 20px;
  /* 输入框和按钮之间的间距 */
}

.input-button-container {
  justify-content: center;
  margin-bottom: 20px;
  /* 输入框和按钮与其他内容的间距 */
}
</style>